<?php defined('SYSPATH') or die('No direct script access.');
                          
class Forum_Controller extends Template_Controller 
{
	public $template = 'layout/forum';
	
	public function __construct()
	{
		parent::__construct();
		
		$user = new Customer_Model();

		$this->db = new Database();
		
		$this->db->update('forum_categories', array('today_posts'=>0, 'today_date'=>date('Y-m-d')), 'DATEDIFF(CURDATE(), today_date) >= 1');
		
		$this->template->menu = '';
		$this->template->content = '';
		$this->template->user = $user->orderby('created_at', 'desc')->limit(1)->find();
	}
	
	public function index()
	{
		$view = new View('forum/home');
		$view->category = $this->db->query('SELECT * FROM forum_categories WHERE left_id>1 AND right_id <(SELECT right_id FROM forum_categories WHERE id=1) AND layer_id<=2 ORDER BY left_id');

		$this->template->content =  $view->render();
	}
		
	public function category($category_id, $page_no)
	{
		$topic = new Forum_Topic_Model();
		
		$page_size = 20;
		
		$this->pagination = new Pagination(array(
	        'base_url'    => 'forum/category/'.$category_id, 
	        'uri_segment' => 4, 
			'items_per_page' => $page_size, 
	        'total_items' => $topic->select('COUNT(*) AS records_found')
								   ->where('category_id', $category_id)
								   ->find()->records_found
	    ));
		
		$view = new View('forum/category');
		$view->category = new Forum_Category_Model($category_id);
		$view->topics = $topic->where('category_id', $category_id)
							  ->orderby('last_post_at', 'desc')
							  ->limit($page_size, (($page_no - 1) * $page_size))
							  ->find_all();
							  
		$this->template->content =  $view->render();
	}
	
	public function topic($category_id, $topic_id, $page_no)
	{
		$prev_topic = new Forum_Topic_Model();
		$next_topic = new Forum_Topic_Model();
		$reply = new Forum_Reply_Model();
		
		$page_size = 10;
		
		$this->pagination = new Pagination(array(
	        'base_url'    => 'forum/topic/'.$category_id.'/'.$topic_id, 
	        'uri_segment' => 5, 
			'items_per_page' => $page_size, 
	        'total_items' => $reply->select('COUNT(*) AS records_found')
								   ->where('topic_id', $topic_id)
								   ->find()->records_found
	    ));
		
		$view = new View('forum/topic');
		$view->category = new Forum_Category_Model($category_id);
		$view->topic = new Forum_Topic_Model($topic_id);
		$view->replies = $reply->where('topic_id', $topic_id)->limit($page_size, (($page_no - 1) * $page_size))->find_all();
		$view->prev_topic = $prev_topic->where("last_post_at>'".$view->topic->last_post_at."'")->orderby('last_post_at', 'asc')->limit(1)->find();
		$view->next_topic = $next_topic->where("last_post_at<'".$view->topic->last_post_at."'")->orderby('last_post_at', 'desc')->limit(1)->find();
		
		$view->topic->views += 1;
		$view->topic->save();
		
		$this->template->content =  $view->render();
	}
	
	public function newtopic($category_id)
	{
		if(cookie::get('userid'))
		{
			$view = new View('forum/newtopic');
			$view->category = new Forum_Category_Model($category_id);
			$this->template->content =  $view->render();
		}
		else
		{
			$this->template->content =  new View('forum/login', array('returnurl'=>'forum/newtopic/'.$category_id));
		}
	}
	
	public function savenewtopic($category_id)
	{
		if( $_POST['message'] )
		{
			$category = new Forum_Category_Model($category_id);
			$topic = new Forum_Topic_Model();
			$reply = new Forum_Reply_Model();
			
			$topic->category_id = $category_id;
			$topic->subject = $_POST['subject'];
			$topic->author = cookie::get('username');
			$topic->author_id = cookie::get('userid');
			$topic->last_post_at = date('Y-m-d H:i:s');
			$topic->last_poster = cookie::get('username');
			$topic->created_at = date('Y-m-d H:i:s');
			
			$topic->save();
			
			$reply->category_id = $category_id;
			$reply->topic_id = $topic->id;
			$reply->subject = $_POST['subject'];
			$reply->message = $_POST['message'];
			$reply->author = cookie::get('username');
			$reply->author_id = cookie::get('userid');
			$reply->useip = myfuns::getip();
			$reply->created_at = date('Y-m-d H:i:s');
			
			$reply->save();
			
			if(isset($_FILES['photo']['tmp_name']) and $_FILES['photo']['tmp_name']) 
			{
				$path = pathinfo($_FILES['photo']['name']);
				$newfilename = realpath('resource/forum') .'/'. date('Ym') .'/'. $reply->id .'.'. strtolower($path['extension']);
				if(file_exists($newfilename)) unlink($newfilename);
				myfuns::move($_FILES['photo']['tmp_name'], $newfilename);
				
				$reply->photo = date('Ym') .'/'. $reply->id .'.'. strtolower($path['extension']);
				$reply->save();
			}
			
			$category->last_topic_id = $topic->id;
			$category->last_topic = $topic->subject;
			$category->last_topic_username = $topic->author;
			$category->last_topic_userid = $topic->author_id;
			$category->last_topic_at = $topic->created_at;
			$category->topics += 1;
			$category->posts += 1;
			$category->today_posts += 1;
			
			$category->save();
		}
		
		url::redirect('forum/category/'.$category_id.'/1', 301);
	}
	
	public function savereply($category_id, $topic_id)
	{
		if( $_POST['message'] )
		{
			$category = new Forum_Category_Model($category_id);
			$topic = new Forum_Topic_Model($topic_id);
			$reply = new Forum_Reply_Model();
			
			$reply->category_id = $category_id;
			$reply->topic_id = $topic->id;
			$reply->subject = $_POST['subject'];
			$reply->message = $_POST['message'];
			$reply->author = cookie::get('username');
			$reply->author_id = cookie::get('userid');
			$reply->useip = myfuns::getip();
			$reply->created_at = date('Y-m-d H:i:s');
			
			$reply->save();
			
			$topic->last_post_at = date('Y-m-d H:i:s');
			$topic->last_poster = cookie::get('username');
			$topic->replies += 1;
			
			$topic->save();
			
			if(isset($_FILES['photo']['tmp_name']) and $_FILES['photo']['tmp_name']) 
			{
				$path = pathinfo($_FILES['photo']['name']);
				$newfilename = realpath('resource/forum') .'/'. date('Ym') .'/'. $reply->id .'.'. strtolower($path['extension']);
				if(file_exists($newfilename)) unlink($newfilename);
				myfuns::move($_FILES['photo']['tmp_name'], $newfilename);
				
				$reply->photo = date('Ym') .'/'. $reply->id .'.'. strtolower($path['extension']);
				$reply->save();
			}
			
			$category->posts += 1;
			$category->today_posts += 1;
			
			$category->save();
		}

		url::redirect('forum/topic/'.$category_id.'/'.$topic_id.'/1', 301);
	}
	
	public function replytopic($category_id, $topic_id)
	{
		if(cookie::get('userid'))
		{
			$view = new View('forum/replytopic');
			$view->category = new Forum_Category_Model($category_id);
			$view->topic = new Forum_Topic_Model($topic_id);
			$this->template->content =  $view->render();
		}
		else
		{
			$this->template->content =  new View('forum/login', array('returnurl'=>'forum/replytopic/'.$category_id.'/'.$topic_id));
		}
	}

	public function login()
	{
		$this->template->content =  new View('forum/login',  array('returnurl'=>$_SERVER['HTTP_REFERER']));
	}
	
	public function checklogin()
	{
		$db = new Database();
		
		$result = $db->query("SELECT id, username, firstname, lastname FROM customers WHERE username='".$_POST['username']."' AND password='".base64_encode($_POST['password'])."'");

		foreach($result as $item)
		{
			cookie::set('userid', $item->id);
			cookie::set('username', $item->username);
			cookie::set('firstname', $item->firstname);
			cookie::set('lastname', $item->lastname);
		}
	
		$url = isset($_POST['returnurl']) ? $_POST['returnurl'] : $_SERVER['HTTP_REFERER'];
	
		url::redirect($url, 301);
		exit;
	}

}